
package com.kehutong.common;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;

public final class Sets {

	private Sets() {
	}

	public static <E> HashSet<E> newHashSet() {
		return new HashSet<E>();
	}

	@SuppressWarnings("unchecked")
	public static <E> HashSet<E> newHashSet(E... elements) {
		int capacity = capacity(elements.length);
		HashSet<E> set = new HashSet<E>(capacity);
		Collections.addAll(set, elements);
		return set;
	}

	public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
		return new HashSet<E>(capacity(expectedSize));
	}

	public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
		if (elements instanceof Collection) {
			Collection<? extends E> collection = (Collection<? extends E>) elements;
			return new HashSet<E>(collection);
		} else {
			return newHashSet(elements.iterator());
		}
	}

	public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
		HashSet<E> set = newHashSet();
		while (elements.hasNext()) {
			set.add(elements.next());
		}
		return set;
	}

	public static <E> LinkedHashSet<E> newLinkedHashSet() {
		return new LinkedHashSet<E>();
	}

	public static <E> LinkedHashSet<E> newLinkedHashSet(Iterable<? extends E> elements) {
		if (elements instanceof Collection) {
			Collection<? extends E> collection = (Collection<? extends E>) elements;
			return new LinkedHashSet<E>(collection);
		} else {
			LinkedHashSet<E> set = newLinkedHashSet();
			for (E element : elements) {
				set.add(element);
			}
			return set;
		}
	}

	static int capacity(int expectedSize) {
		return Math.max(expectedSize * 2, 16);
	}
}
